package com.starblink.android.basic.base.activity

import android.os.Bundle
import androidx.lifecycle.Observer
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.android.basic.widget.gloading.Gloading
import com.starblink.basic.util.NetWorkUtil
import com.starblink.basic.util.log.YYLogUtils

/**
 * 加入ViewModel与LoadState
 * 默认为布局加载的方式
 */
abstract class BaseVMLoadingActivity<VM : BaseViewModel> : AbsVMActivity<VM>() {


    protected val mGLoadingHolder by lazy {
        generateGLoading()
    }

    //如果要替换GLoading，重写次方法
    open protected fun generateGLoading(): Gloading.Holder {
        return Gloading.getDefault().wrap(this).withRetry {
            onGoadingRetry()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutIdRes())
        viewModel.getActionLiveData().observe(this, stateObserver)
        startObserve()
    }

    abstract fun getLayoutIdRes(): Int
    abstract fun startObserve()
    protected open fun onGoadingRetry() {
    }

    override fun onNetworkConnectionChanged(
        isConnected: Boolean,
        networkType: NetWorkUtil.NetworkType?
    ) {
        YYLogUtils.i("")
    }
    // ================== 网络状态的监听 ======================

    private var stateObserver: Observer<LoadAction> = Observer { loadAction ->
        if (loadAction != null) {

            when (loadAction.action) {
                LoadAction.STATE_NORMAL -> showStateNormal()
                LoadAction.STATE_ERROR -> showStateError(loadAction.message)
                LoadAction.STATE_SUCCESS -> showStateSuccess()
                LoadAction.STATE_LOADING -> showStateLoading()
                LoadAction.STATE_NO_DATA -> showStateNoData()
                LoadAction.STATE_PROGRESS -> showStateProgress()
                LoadAction.STATE_HIDE_PROGRESS -> hideStateProgress()
            }

        }
    }

    protected open fun showStateNormal() {}

    protected open fun showStateLoading() {
        mGLoadingHolder.showLoading()
    }

    protected open fun showStateSuccess() {
        mGLoadingHolder.showLoadSuccess()
    }

    protected open fun showStateError(message: String?) {
        mGLoadingHolder.showLoadFailed(message)
    }

    protected open fun showStateNoData() {
        mGLoadingHolder.showEmpty()
    }

    protected fun showStateProgress() {
        LoadingDialogManager.get().showLoading(mActivity)
    }

    protected fun hideStateProgress() {
        LoadingDialogManager.get().dismissLoading()
    }

}